package sixyz.controller;

import sixyz.entity.value.Message;
import sixyz.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/login")
public class UserLoginServlet extends HttpServlet {

    private final UserService userService = new UserService();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取客户端传来的参数
        String account = req.getParameter("account");
        String password = req.getParameter("password");
        // 调用service方法，返回消息对象模型
        try {
            Message message = userService.userLogin(account, password);
            // 如果状态码为1，表示登陆成功
            if (message.getStatusCode() == 1) {
                // 登录成功，在session中记录user对象
                req.getSession().setAttribute("user", message.getObject());
                // 重定向至聊天界面
                resp.sendRedirect("index.jsp");
            } else {
                // 登陆失败，将消息模型记录在request对象中，请求转发到login.jsp
                req.setAttribute("message", message);
                req.getRequestDispatcher("login.jsp").forward(req,resp);
            }
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
